package control

import (
	"asystem/db"
	"asystem/pays/alipay"
	"asystem/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
	"time"
)

var (
	workType string
	reqUrl   string
)

type workDat struct {
	WuLiuId    string `json:"wuLiuId"`
	ExpressNum string `json:"expressNum"`
	Addr       string `json:"addr"`
	WorkType   int    `json:"workType"`
	SaleId     int    `json:"sale_id"`
	WorkInfo   struct {
		Type  []string `json:"type"`
		Name  []string `json:"name"`
		Num   []string `json:"num"`
		Fault []string `json:"fault"`
	} `json:"workInfo"`
}

func index(c *gin.Context) {
	se := utils.InitSession(c, "client")
	phone := se.GetSession(se.SesKey.CliSessKey)
	if phone == "" {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("后台服务器错误，给您带来不便抱歉！")})
		return
	}
	// 根据手机号获取客户名
	model := &db.Model{Client: &db.Client{Phone: phone.(string)}}
	name, err := db.GetClientName(model)
	if err != nil {
		c.HTML(200, "template/index.html", gin.H{"title": "链力", "name": ""})
		return
	}
	c.HTML(200, "template/index.html", gin.H{"title": "链力", "name": name})
}

// 客户登录方法
func cSign(c *gin.Context) {
	if c.Request.Method == "POST" {
		username := c.PostForm("username")
		if username == "" {
			c.JSON(200, gin.H{"success": "", "errMsg": "登录失败！您还没有输入任何登录信息哦~~！"})
			return
		}
		model := &db.Model{Client: &db.Client{Phone: username}}
		bl, err := db.GetClientIsNull(model)
		if err != nil {
			c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
			return
		}
		if !bl {
			c.JSON(200, gin.H{"success": "", "errMsg": "登录失败~此号码不存在~!"})
			return
		}
		// 设置 session
		se := utils.InitSession(c, "client")
		if err = se.SetSession(se.SesKey.CliSessKey, username); err != nil {
			c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
			return
		}
		c.JSON(200, gin.H{"success": "loginSuccess", "errMsg": ""})
		return
	}
	c.HTML(200, "template/clogin.html", gin.H{"title": "链力"})
}

// cLogout 退出登录方法
func cLogout(c *gin.Context) {
	se := utils.InitSession(c, "client")
	se.DelSession(se.SesKey.CliSessKey)
	c.JSON(200, gin.H{"success": "success", "errMsg": ""})
}

// 客户注册实现方法
func registryUser(c *gin.Context) {
	if c.Request.Method == "POST" {
		username := c.PostForm("username")
		phone := c.PostForm("phone")
		model := &db.Model{Client: &db.Client{
			ClientName: username,
			Phone:      phone,
		}}
		ret, _ := db.PhoneGetClient(model.Client.Phone)
		if ret != "" {
			c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("此号码已存在，请更换号码再次进行添加，谢谢!")})
			return
		}
		if err := db.InsertUserDatToSql(model); err != nil {
			c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
			return
		}
		c.JSON(200, gin.H{"success": "success", "errMsg": ""})
		return
	}
	sales, err := db.GetSalePeople()
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.HTML(200, "template/register.html", gin.H{"title": "链力", "sales": sales})
}

// getUserInfo 根据 session 中的数据从数据库获取客户姓名
func getUserInfo(c *gin.Context) {
	se := utils.InitSession(c, "client")
	phone := se.GetSession(se.SesKey.CliSessKey)
	if phone == "" {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("后台服务器错误，给您带来不便抱歉！")})
		return
	}
	model := &db.Model{Client: &db.Client{Phone: phone.(string)}}
	name, err := db.GetClientUserName(model)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": map[string]string{"name": name, "phone": phone.(string)}, "errMsg": ""})
}

// getUserAddress 根据用户信息获取用户的地址
func getUserAddress(c *gin.Context) {
	se := utils.InitSession(c, "client")
	phone := se.GetSession(se.SesKey.CliSessKey)
	if phone == "" {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("后台服务器错误，给您带来不便抱歉！")})
		return
	}
	model := &db.Model{Client: &db.Client{Phone: phone.(string)}}
	cid, err := db.GetUserIdDat(model)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	model = &db.Model{Client: &db.Client{Cid: cid, Phone: phone.(string)}}
	addr, err := db.GetClientAddress(model)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": addr, "errMsg": ""})
}

// 获取所有物流数据
func getAllWuLiu(c *gin.Context) {
	logs, err := db.GetLogTicsDat()
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": logs, "errMsg": ""})
}

// 获取销售业务人员数据
func getSaleDat(c *gin.Context) {
	sales, err := db.GetAllSaleAndBusiness()
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": sales, "errMsg": ""})
}

// 点击添加设备按钮获取所有设备类型数据
func getMaterType(c *gin.Context) {
	materTypes, err := db.GetALlMaterType()
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": materTypes, "errMsg": ""})
}

// 根据选择的物料类型获取相对应类型的物料数据
func getMaterDat(c *gin.Context) {
	mtId, err := strconv.Atoi(c.Query("mt_id"))
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("提交是物料类型数据错误，错误代码：%v", err)})
		return
	}
	model := &db.Model{MaterType: &db.MaterType{
		MtId: mtId,
	}}
	maters, err := db.GetTypeMaterDat(model)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": maters, "errMsg": ""})
}

// getProvinceDat 获取所有省份信息控制函数
func getProvinceDat(c *gin.Context) {
	provinces, err := db.GetProvinceDat()
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": provinces, "errMsg": ""})
}

// getCityDat 获取所有市级信息控制函数
func getCityDat(c *gin.Context) {
	proId, err := strconv.Atoi(c.Query("pro_id"))
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("抱歉~提交的省份Id 数据类型错误，错误代码：%v", err)})
		return
	}
	cityArray, err := db.GetProCityDat(proId)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": cityArray, "errMsg": ""})
}

// insertAddrToSql 添加客户地址到数据库
func insertAddrToSql(c *gin.Context) {
	addr := c.PostForm("addr")
	option := c.PostForm("option")
	// 获取用户 id
	se := utils.InitSession(c, "client")
	phone := se.GetSession(se.SesKey.CliSessKey)
	if phone == "" {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("后台服务器错误，给您带来不便抱歉！")})
		return
	}
	model := &db.Model{Client: &db.Client{Phone: phone.(string)}}
	cid, err := db.GetUserIdDat(model)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	// 添加客户地址到数据库
	model = &db.Model{ClientAddr: &db.ClientAddr{ClientId: cid, Addr: addr}}
	if err = db.InsertClientAddrToSql(option, model); err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": "success", "errMsg": ""})
}

// addWorkDat 添加工单数据
func addWorkDat(c *gin.Context) {
	se := utils.InitSession(c, "client")
	phone := se.GetSession(se.SesKey.CliSessKey)
	model := &db.Model{Client: &db.Client{Phone: phone.(string)}}
	cid, err := db.GetUserIdDat(model)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("添加工单失败，错误代码:%v", err)})
		return
	}
	// get saleId
	//model = &db.Model{Client: &db.Client{Cid: cid}}
	//sid, err := db.GetSaleId(model)
	//if err != nil {
	//	fmt.Println("=================================>", err)
	//	c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf(":%v", err)})
	//	return
	//}
	var work *workDat = &workDat{}
	err = c.ShouldBindJSON(&work)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("添加工单数据失败，错误代码：%v", err)})
		return
	}
	wuLiuTypeId := work.WuLiuId
	expressNum := work.ExpressNum
	_ = work.Addr
	workTypeId := work.WorkType
	lid, err := utils.StrToInt(wuLiuTypeId)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf(":%v", err)})
		return
	}
	switch workTypeId {
	case 1:
		workType = "返修工单"
	case 2:
		workType = "维修工单"
	case 3:
		workType = "服务申请"
	}
	for i := 0; i < len(work.WorkInfo.Type); i++ {
		mid, err := utils.StrToInt(work.WorkInfo.Name[i])
		if err != nil {
			c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf(":%v", err)})
			return
		}
		materNum, err := utils.StrToInt(work.WorkInfo.Num[i])
		if err != nil {
			c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf(":%v", err)})
			return
		}
		model = &db.Model{Work: &db.Work{
			Process:       0,                                        // 流程控制,新建工单流程为 0
			State:         0,                                        // 工单状态,新建工单状态为 0
			MId:           mid,                                      // 关联的物料Id
			UId:           work.SaleId,                              // 关联的销售Id
			CId:           cid,                                      // 客户Id
			LId:           lid,                                      // 关联的物流名称Id
			WorkType:      workType,                                 // 工单类型
			MaterNum:      materNum,                                 // 物料数量
			IssueDescribe: work.WorkInfo.Fault[i],                   // 问题描述
			LogNum:        expressNum,                               // 快递单号
			CreateDate:    time.Now().Format("2006-01-02 03:04:05"), // 创建时间
		}}
		if err = db.InsertWorkInfoToSql(model); err != nil {
			c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf(":%v", err)})
			return
		}
	}

	workArray, err := db.GetWorkIdAndType(expressNum)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf(":%v", err)})
		return
	}
	for _, val := range workArray {
		upcoming := &db.UpComing{
			WID:    val.Wid,      // 关联的工单Id
			UID:    val.UId,      // 关联的销售Id
			MID:    val.MId,      // 关联的物料Id
			StatId: 0,            // 待办事件状态，创建工单时为 0
			UpName: val.WorkType, // 待办事件名称
		}
		if err = db.InsertDatToUpcoming(upcoming); err != nil {
			c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf(":%v", err)})
			return
		}
	}
	c.JSON(200, gin.H{"success": "创建工单成功", "errMsg": ""})
}

// getWorkOrder 客户获取工单信息
func getWorkOrder(c *gin.Context) {
	se := utils.InitSession(c, "client")
	phone := se.GetSession(se.SesKey.CliSessKey)
	model := &db.Model{Client: &db.Client{Phone: phone.(string)}}
	cid, err := db.GetUserIdDat(model)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	statId := c.Query("statId")
	works, err := db.GetWorkOrderDat(statId, cid)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": works, "errMsg": ""})
}

// getSearchWorkDat 通过搜索获取工单信息
func getSearchWorkDat(c *gin.Context) {
	se := utils.InitSession(c, "client")
	phone := se.GetSession(se.SesKey.CliSessKey)
	model := &db.Model{Client: &db.Client{Phone: phone.(string)}}
	cid, err := db.GetUserIdDat(model)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	logNum := c.Query("wid")
	works, err := db.GetSearchWorkDat(logNum, cid)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": works, "errMsg": ""})
}

// codeGetMaterClientDat 根据扫描的条码获取物料及客户相关信息
func codeGetMaterClientDat(c *gin.Context) {
	var isExpire string
	var uinx int
	code := c.Query("find")
	//materId := strings.Split(code, ",")[2]
	clientId, err := strconv.Atoi(strings.Split(code, ",")[3])
	if err != nil {
		c.HTML(200, "template/verify.html", gin.H{"success": "", "errMsg": fmt.Sprintf("错误，给您带来不便敬请谅解，错误代码：%v", err)})
		return
	}
	dats, err := db.GetWarrantDate(code)
	if err != nil {
		fmt.Println("=======================================================>", err)
		c.HTML(200, "template/verify.html", gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	if len(dats) > 0 {
		for _, codes := range dats {
			uinx, err = utils.StrToUnix2(codes.OutLibDate)
		}
	}
	//dats[0].OutLibDate
	//time.Parse()
	//timeStamp := strings.Split(code, ",")[5]
	// 计算当前产品是否已过保
	bol, err := utils.CalTimeEquation(strconv.Itoa(uinx))
	if err != nil {
		c.HTML(200, "template/verify.html", gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	if bol {
		isExpire = "该商品尚在保修期内，请放心使用！"
	} else {
		isExpire = "该商品已过保修期~!"
	}
	// 获取所有物流公司信息
	logDats, err := db.GetLogTicsDat()
	if err != nil {
		c.HTML(200, "template/verify.html", gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	// 将字符串的时间戳转换为指定格式的时间
	timeFat, err := utils.StrToTimeFat(strconv.Itoa(uinx))
	if err != nil {
		c.HTML(200, "template/verify.html", gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	se := utils.InitSession(c, "client")
	phone := se.GetSession(se.SesKey.CliSessKey)
	model := &db.Model{Client: &db.Client{Phone: phone.(string)}}
	cid, err := db.GetUserIdDat(model)
	if err != nil {
		c.HTML(200, "template/verify.html", gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	// 获取客户姓名
	cliName, err := db.GetClientName(model)
	if err != nil {
		c.HTML(200, "template/verify.html", gin.H{"success": "", "name": cliName, "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	model = &db.Model{Client: &db.Client{Cid: cid, Phone: phone.(string)}}
	// 获取用户地址
	cliAddr, err := db.GetClientAddress(model)
	if err != nil {
		c.HTML(200, "template/verify.html", gin.H{"success": "", "name": cliName, "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	// 根据条码获取物料Id
	materId, err := db.GetMaterId(code)
	if err != nil {
		c.HTML(200, "template/verify.html", gin.H{"success": "", "name": cliName, "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	// 根据物料 Id 获取商品信息
	materSlice, err := db.GetIdMaterInfo(strconv.Itoa(materId))
	if err != nil {
		c.HTML(200, "template/verify.html", gin.H{"success": "", "name": cliName, "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	// 获取所有销售人员信息
	saleSlice, err := db.GetSalePeople()
	if err != nil {
		c.HTML(200, "template/verify.html", gin.H{"success": "", "name": cliName, "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	// 判断如果当前登录客户与条码中绑定的客户是否一致,不一致则提示产品已注册给其他人
	if cid != clientId { //
		c.HTML(200, "template/verify.html", gin.H{
			"title":    "链力",
			"success":  "success",
			"addr":     cliAddr,
			"time":     timeFat,
			"logDats":  logDats,
			"isExpire": isExpire,
			"mater":    materSlice,
			"name":     cliName,
			"sales":    saleSlice,
			"myPro":    "若有商品需要进行售后 / 维修服务请点击"})
		return
	}
	if len(materSlice) > 0 {
		c.HTML(200, "template/verify.html", gin.H{
			"title":    "链力",
			"success":  "success",
			"addr":     cliAddr,
			"time":     timeFat,
			"logDats":  logDats,
			"isExpire": isExpire,
			"mater":    materSlice,
			"name":     cliName,
			"sales":    saleSlice,
			"myPro":    ""})
		return
	}
	c.HTML(200, "template/verify.html", gin.H{"success": "", "name": cliName, "title": "链力", "errMsg": fmt.Sprintf("%v", err)})
}

// verifyCreateWorkOrder 验证物料页面创建工单信息
func verifyCreateWorkOrder(c *gin.Context) {
	type workDat struct {
		WType         int    `json:"WType"`
		MaterId       string `json:"materId"`
		UserAddr      string `json:"userAddr"`
		ExpressName   string `json:"expressName"`
		ExpressNumber string `json:"expressNumber"`
		ProDesc       string `json:"proDesc"`
	}
	se := utils.InitSession(c, "client")
	phone := se.GetSession(se.SesKey.CliSessKey)
	model := &db.Model{Client: &db.Client{Phone: phone.(string)}}
	cid, err := db.GetUserIdDat(model)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("添加工单失败，错误代码:%v", err)})
		return
	}
	model = &db.Model{Client: &db.Client{Cid: cid}}
	sid, err := db.GetSaleId(model)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf(":%v", err)})
		return
	}

	workData := &workDat{}
	if err = c.ShouldBindJSON(&workData); err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("添加工单数据失败，错误代码：%v", err)})
		return
	}
	lid, err := strconv.Atoi(workData.ExpressName)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("添加工单数据失败，错误代码：%v", err)})
		return
	}
	mid, err := strconv.Atoi(workData.MaterId)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("添加工单数据失败，错误代码：%v", err)})
		return
	}
	switch workData.WType {
	case 1:
		workType = "返修工单"
	case 2:
		workType = "维修工单"
	case 3:
		workType = "服务申请"
	}
	workInfo := &db.Model{Work: &db.Work{
		Process:       0,                                        // 流程控制,新建工单流程为 0
		State:         0,                                        // 工单状态,新建工单状态为 0
		MId:           mid,                                      // 关联的物料Id
		UId:           sid,                                      // 关联的销售Id
		CId:           cid,                                      // 客户Id
		LId:           lid,                                      // 关联的物流名称Id
		WorkType:      workType,                                 // 工单类型
		MaterNum:      1,                                        // 物料数量
		IssueDescribe: workData.ProDesc,                         // 问题描述
		LogNum:        workData.ExpressNumber,                   // 快递单号
		CreateDate:    time.Now().Format("2006-01-02 03:04:05"), // 创建时间
	}}
	if err = db.InsertWorkInfoToSql(workInfo); err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf(":%v", err)})
		return
	}

	// 插入数据到待办事项表
	workArray, err := db.GetWorkIdAndType(workData.ExpressNumber)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf(":%v", err)})
		return
	}
	for _, val := range workArray {
		upcoming := &db.UpComing{
			WID:    val.Wid,      // 关联的工单Id
			UID:    val.UId,      // 关联的销售Id
			MID:    val.MId,      // 关联的物料Id
			StatId: 0,            // 待办事件状态，创建工单时为 0
			UpName: val.WorkType, // 待办事件名称
		}
		if err = db.InsertDatToUpcoming(upcoming); err != nil {
			c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf(":%v", err)})
			return
		}
	}
	c.JSON(200, gin.H{"success": "success", "errMsg": ""})
}

// getRepairWorkDat 获取维修工单数据信息
func getRepairWorkDat(c *gin.Context) {
	orderTpeId := c.Query("orderType")
	se := utils.InitSession(c, "client")
	phone := se.GetSession(se.SesKey.CliSessKey)
	model := &db.Model{Client: &db.Client{Phone: phone.(string)}}
	cid, err := db.GetUserIdDat(model)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("添加工单失败，错误代码:%v", err)})
		return
	}
	repairWorkDats, err := db.GetRepairWorkDat(orderTpeId, cid)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": repairWorkDats, "errMsg": ""})
}

// getWorkOrderDat 客户手机端获取工单信息
func getWorkOrderDat(c *gin.Context) {
	wType := c.Query("searchType")
	se := utils.InitSession(c, "client")
	phone := se.GetSession(se.SesKey.CliSessKey)
	model := &db.Model{Client: &db.Client{Phone: phone.(string)}}
	cid, err := db.GetUserIdDat(model)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("添加工单失败，错误代码:%v", err)})
		return
	}
	data, err := db.ClientGetWorkDat(wType, cid)
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.JSON(200, gin.H{"success": data, "dataLen": len(data), "errMsg": ""})
}

// 阿里支付
func aliPay(c *gin.Context) {
	// 需要在这里获取前端传过来的数据
	ali, err := alipay.InitAliClient()
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("初始化阿里支付客户端失败，错误代码:%v", err)})
		return
	}
	reqUrl = c.Query("url")
	ali.Pay(c)
}

func aliPayCallback(c *gin.Context) {
	//ali, err := alipay.InitAliClient()
	//if err != nil {
	//	c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("初始化阿里支付客户端失败，错误代码:%v", err)})
	//	return
	//}
	outTradeNo := c.Query("out_trade_no")
	amount := c.Query("total_amount")
	// 修改支付订单状态

	if err := db.UpdatePayOrderState(outTradeNo[12:], amount); err != nil {
		c.HTML(200, "template/payNotice.html", gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	// 修改工单状态  ll165914378671
	if err := db.UpdateWorkStatus(outTradeNo[12:]); err != nil {
		c.HTML(200, "template/payNotice.html", gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}

	data, err := db.GetAdData()
	if err != nil {
		c.HTML(200, "template/payNotice.html", gin.H{"success": "", "errMsg": fmt.Sprintf("%v", err)})
		return
	}
	c.HTML(200, "template/payNotice.html", gin.H{"title": "链力", "order_id": outTradeNo, "amount": amount, "requrl": reqUrl, "shopping_url": data})
}

func aliPayNotify(c *gin.Context) {
	ali, err := alipay.InitAliClient()
	if err != nil {
		c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("初始化阿里支付客户端失败，错误代码:%v", err)})
		return
	}
	ali.AliNotify(c)
}
